package com.buba.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

/**
 * @description:
 * @Author: 游王子
 * @date: 2021/8/20 16:22
 */
@SpringBootConfiguration
public class SpringConfig {
    /**
     * 方法描述 自定义领域 （包含了验证和授权）
     *
     * @param
     * @author:
     * @return: com.buba.config.CustomRealm
     * @date: 2021/8/20
     */
    @Bean
    public CustomRealm customRealm() {
        CustomRealm customRealm=new CustomRealm();
        customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return customRealm;
    }
    //密码比较器
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    /**
     * 方法描述 默认的shiro web安全管理器
     *
     * @param
     * @author:
     * @return: org.apache.shiro.web.mgt.DefaultWebSecurityManager
     * @date: 2021/8/20
     */
    @Bean
    public DefaultWebSecurityManager getDefaultSecurityManager() {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        // 向安全管理器中添加领域
        defaultSecurityManager.setRealm(customRealm());
        return defaultSecurityManager;
    }

    /**
     * 方法描述 定义默认shiro过滤链
     * @author:
     * @param
     * @return: org.apache.shiro.spring.web.config.ShiroFilterChainDefinition
     * @date: 2021/8/23
     */
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        // 定义默认shiro过滤链
        DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
        // 主要定义匿名访问的路径 anon 表示可以匿名访问路径
        definition.addPathDefinition("/login.html","anon");
        definition.addPathDefinition("/register.html","anon");
        definition.addPathDefinition("/UserController/login","anon");
        definition.addPathDefinition("/UserController/register","anon");
        definition.addPathDefinition("/UserController/*","anon");
        definition.addPathDefinition("/style/**","anon");
        // 定义哪些资源需要认证才能访问 authc 表示需要认证
        definition.addPathDefinition("/**","authc");
        return definition;
    }
}
